package pdm.yamba.dataAccess;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DBProvider {
	
	
	  public static final String KEY_ROWID = "id";
	  public static final String KEY_MESSAGE = "message";
	  private static final String DATABASE_NAME = "YambaDB";
	  private static final String DATABASE_TABLE = "tweets";
	  private static final String DATABASE_CREATE = "create table tweets (id integer primary key autoincrement, message text not null);";
	  private final Context context;
	  private DatabaseHelper DBHelper;
	  private SQLiteDatabase db;
	 
	  public DBProvider(Context context) {
	    this.context = context;
	    DBHelper = new DatabaseHelper(context);
	  }
	 
	  private static class DatabaseHelper extends SQLiteOpenHelper {
	    DatabaseHelper(Context context) {
	      super(context, DATABASE_NAME, null, 1);
	    }
	 
	    @Override
	    public void onCreate(SQLiteDatabase db) {
	      try {
	        db.execSQL(DATABASE_CREATE);
	      } catch (SQLException e) {
	        e.printStackTrace();
	      }
	    }
	 
	    @Override
	    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
	      Log.w("Yamba", oldVersion + " to " + newVersion + ", which will destroy all old data");
	      db.execSQL("DROP TABLE IF EXISTS tweets");
	      onCreate(db);
	    }
	  }
	 
	  public DBProvider open() throws SQLException {
	    db = DBHelper.getWritableDatabase();
	    return this;
	  }
	 
	  public void close() {
	    DBHelper.close();
	  }
	 
	  public long insertMessage(String message) {
	    ContentValues initialValues = new ContentValues();
	    initialValues.put(KEY_MESSAGE, message);
	    return db.insert(DATABASE_TABLE, null, initialValues);
	  }
	 
	  public boolean deleteMessage(long rowId) {
	    return db.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
	  }
	 
	  public Cursor getAllMessages() {
	    return db.query(DATABASE_TABLE, new String[] { KEY_ROWID, KEY_MESSAGE }, null, null, null, null, null);
	  }
	 
	  public Cursor getMessage(long rowId) throws SQLException {
	    Cursor mCursor = db.query(true, DATABASE_TABLE, new String[] { KEY_ROWID, KEY_MESSAGE }, KEY_ROWID + "=" + rowId, null, null, null, null, null);
	    if (mCursor != null) {
	      mCursor.moveToFirst();
	    }
	    return mCursor;
	  }
	 
	  public boolean updateMessage(long rowId, String message) {
	    ContentValues args = new ContentValues();
	    args.put(KEY_MESSAGE, message);
	    return db.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;
	  }
	}
